﻿using B.Z.BasicData.Infrastructure;
using B.Z.Inventory.API.Write.Application.Command;
using B.Z.Inventory.Domain;
using B.Z.Inventory.ErrorCode;
using MediatR;

namespace B.Z.Inventory.API.Write.Application.CommandHandler
{
    public class InventoryGoodsAddCommandHandler : IRequestHandler<InventoryGoodsAddCommand, APIResult<int>>
    {
        private readonly IBaseRepository<T_InventoryGoods> inventorygoodsRepository;
        private readonly IBaseRepository<T_InventoryTask> taskRepository;
        private readonly ILogger<InventoryGoodsAddCommandHandler> logger;
        public InventoryGoodsAddCommandHandler(IBaseRepository<T_InventoryGoods> inventorygoodsRepository, ILogger<InventoryGoodsAddCommandHandler> logger, IBaseRepository<T_InventoryTask> taskRepository)
        {
            this.inventorygoodsRepository = inventorygoodsRepository;
            this.logger = logger;
            this.taskRepository = taskRepository;
        }

        public async Task<APIResult<int>> Handle(InventoryGoodsAddCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> result = new APIResult<int>();
            result.Code = APIEnums.ok;
            result.Message = "配置成功";
            var idList = request.Ids.Split(',').Select(x => Convert.ToInt32(x));
            var lists = inventorygoodsRepository.GetAll().Where(x => x.InventoryId == request.Id).ToList();
            inventorygoodsRepository.Del(lists);

            using (var rs = inventorygoodsRepository.Context.Database.BeginTransaction()) 
            {
                try
                {
                    var model = taskRepository.GetAll().FirstOrDefault(x => x.Id == request.Id);
                    model.InventoryStatus = 1;
                    model.IsHaveGoods = true;
                    await taskRepository.Update(model);

                    List<T_InventoryGoods> list = new() { };
                    foreach (var item in idList)
                    {
                        T_InventoryGoods goods = new T_InventoryGoods();
                        goods.InventoryId = request.Id;
                        goods.GoodsId = item;
                        list.Add(goods);
                    }
                    result.Data = await inventorygoodsRepository.AddRange(list);

                    rs.Commit();
                }
                catch (Exception ex)
                {

                    rs.Rollback();
                }
            }

            
            return Task.FromResult(result).Result;
        }
    }
}
